<?php

namespace backend\models;

use frontend\models\UserCoupon;
use Yii;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "prf_coupon".
 *
 * @property integer $id
 * @property string $name
 * @property string $title
 * @property string $memo
 * @property integer $img_id
 * @property string $action
 * @property integer $action_id
 * @property string $url
 * @property integer $start_time
 * @property integer $end_time
 * @property string $coupon_rule
 * @property string $coupon_price
 * @property string $price
 * @property integer $totle_count
 * @property integer $last_count
 * @property integer $user_max_number
 * @property string $user_types
 * @property integer $state
 * @property integer $time_state
 * @property string $excode
 * @property integer $shipping
 */
class PrfCoupon extends \yii\db\ActiveRecord
{
    const SCENARIO_CREATE = 'create';

    public $imageFile;
    public $class1, $class2, $class3;
    public $canTrans;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'prf_coupon';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'title', 'action','coupon_rule', 'price', 'user_max_number', 'state', 'shipping'], 'required'],
            ['imageFile', 'required', 'on' => self::SCENARIO_CREATE],
            [['memo', 'trans_type'], 'string'],
            [['img_id', 'action_id', 'totle_count', 'last_count', 'user_max_number', 'state', 'time_state', 'shipping','class1','class2','class3'], 'integer'],
            [['coupon_price', 'price'], 'number'],
            [['name', 'action'], 'string', 'max' => 32],
            [['coupon_rule'], 'string', 'max' => 20],
            [['user_types', 'excode'], 'string', 'max' => 64],
            ['coupon_price', 'required','when' => function ($model) {
                return $model->coupon_rule == 'M' || $model->coupon_rule == 'N';
            }, 'whenClient' => "function (attribute, value) {
                return $('#prfcoupon-coupon_rule').val() == 'M' || $('#prfcoupon-coupon_rule').val() == 'N';
            }"],
            ['action_id', 'required','when' => function ($model) {
                return $model->action != 'class';
            }, 'whenClient' => "function (attribute, value) {
                return $('#prfcoupon-coupon_rule').val() == 'M' || $('#prfcoupon-coupon_rule').val() == 'N';
            }"],
            ['class1', 'required','when' => function ($model) {
                return $model->action == 'class' && ($model->action_id == '' || $model->action_id == null);
            }, 'on' => self::SCENARIO_CREATE],
            [['imageFile'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
            ['url', 'url', 'defaultScheme' => 'https'],
            ['price','validateRule'],
            ['coupon_rule', 'validateCR'],
            ['action_id', 'validateAcId'],
            ['canTrans', 'validataTrans'],
        ];
    }

    public function validataTrans($attribute) {
        if ($this->canTrans == 1) {
            if ($this->action == 'all') {
                if (empty($this->user_types)) {
                    $this->addError($attribute, '认证vip用户和装饰公司才能转送');
                } else {
                    foreach (array_filter(explode(',', $this->user_types)) as $key => $val) {
                        if (!in_array($val, [3,4])) {
                            $this->addError($attribute, '认证vip用户和装饰公司才能转送');
                            return;
                        }
                    }
                }
            } else {
                $this->addError($attribute, '只有全场优惠券能转送');
            }
        }
    }

    public function validateRule($attribute) {
        if ($this->coupon_rule == 'D') {
            if ($this->$attribute < 0.4 || $this->$attribute >= 1) {
                $this->addError($attribute, '折扣率要在0.4-1之间');
            }
        }
    }

    public function validateCR($attribute) {
        if ($this->action == 'all') {
            if ($this->$attribute !== 'D') {
                $this->addError($attribute, '全场券只适用折扣率');
            }
       }
    }
    public function validateAcId($attribute) {
        if ($this->action == 'all') {
            if ($this->$attribute != '0') {
                $this->addError($attribute, '全场券动作id只能是0');
            }
        }
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'imageFile' => '上传优惠券封面',
            'id' => 'ID',
            'name' => '优惠卷名称',
            'title' => '标题-一般为活动名称及条件',
            'memo' => '详细说明',
            'img_id' => 'Img ID',
            'action' => '对象',
            'action_id' => '动作id',
            'url' => '优惠券介绍网址',
            'start_time' => '生效时间',
            'end_time' => '结束时间',
            'coupon_rule' => '规则',
            'coupon_price' => '价格条件',
            'price' => '抵用值',
            'totle_count' => '总数',
            'last_count' => '剩余数量',
            'user_max_number' => '每个用户最多兑换数',
            'user_types' => '适用的用户类型(适用所有则全不选)',
            'state' => '状态',
            'time_state' => ' 使用有效期，默认0，跟随优惠券或输入多少天',
            'excode' => '兑换码',
            'shipping' => '是否包邮',
            'class1' => '一级分类',
            'class2' => '二级分类',
            'class3' => '三级分类',
            'canTrans' => '能否转送',
            'trans_type' => '能否转送',
        ];
    }

    public function upload()
    {
        $dir = self::genAddr(194);
        if (mkdir($dir['path'] . $dir['dir'], 0777, true)) {
            $full_path = $dir['path'] . $dir['dir'] . $dir['name'] . '.' . $this->imageFile->extension;
            $this->imageFile->saveAs($full_path);
            $image_info = getimagesize($full_path);

//            if (self::transportImg($dir['dir'], $dir['name'], $this->imageFile->extension, $full_path)) {
            $this->imageFile = self::saveImg('194', $dir['dir'] . $dir['name'] . '.' . $this->imageFile->extension, $image_info);
            if ($this->imageFile) {
                return $this->imageFile;
            } else {
                echo $this->imageFile;
            }
//        } else {
//            echo "传输出错";
//        }
        }
    }

    //保存图片
    public static function saveImg($type, $path, $info)
    {
        $image = new Image();
        $image->type = $type;
        $image->url = $path;
        $image->name = '优惠券';
        $image->width = $info[0];
        $image->height = $info[1];
        $image->update_time = strtotime('now');
        if ($image->save()) {
            return Yii::$app->db->getLastInsertID();
        } else {
            return false;
        }
    }

    //传输图片到正式服
    public static function transportImg($dir, $name, $imgType, $imgFullPath)
    {
        $url = "https://app.jajahome.com/furniture/calc.php";
        if (class_exists('\CURLFile')) {
            $post_data = [
                "q" => "uploadImg",
                "dir" => $dir,
                "name" => $name,
                "file_type" => $imgType,
                "img" => new \CURLFile($imgFullPath)
            ];
        } else {
            $post_data = [
                "q" => "uploadImg",
                "dir" => $dir,
                "name" => $name,
                "file_type" => $imgType,
                "img" => "@" . realpath($imgFullPath)
            ];
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output == "done";
    }

    //生成身份证和名片目录,参数："id_card"或"card"
    public static function genAddr($type)
    {
        $result = PrfType::find()->where(['id' => $type])->one();
        $uuid = md5(uniqid());
        $uuid_a = substr($uuid, 0, 3);
        $uuid_b = substr($uuid, 3, 3);
        $uuid_c = substr($uuid, 6, 3);
        $uuid_d = substr($uuid, 9, 3);
        $dir = 'images/' . $result->addr . '/' . $uuid_a . '/' . $uuid_b . '/' . $uuid_c . '/' . $uuid_d . '/';
        $name = substr($uuid, 12, 20);
        $path = '../../backend/web/';
//        $path = 'D:\upload/';
        return [
            'path' => $path,
            "dir" => $dir,
            "name" => $name
        ];
    }

    public function getCouponImg()
    {
        return $this->hasOne(Image::className(), ['id' => 'img_id']);
    }

    public function getUserCoupon()
    {
        return $this->hasOne(UserCoupon::className(), ['coupon_id' => 'id'])->andWhere(['uid' => Yii::$app->user->identity->id]);
    }

    //标记优惠券已使用
    public static function useCoupon($user_coupon_arr)
    {
        if (!empty($user_coupon_arr)) {
            $cp = UserCoupon::updateAll(['state' => 1, 'useing_time' => time()], ['and',['in', 'id', $user_coupon_arr], ['state' => 0]]);
            return $cp;
        }
    }
    //计算优惠券使用后的价格
    public static function coupon_calc($item_price, $item_count, $coupon_obj){
        $price=0;
        switch ($coupon_obj['coupon_rule']) {
            //满就减
            case 'M':
                if ($item_price*$item_count >= intval($coupon_obj['coupon_price'])) {
                    $price = $item_price*$item_count-intval($coupon_obj['price']);
                }else{
                    $price = $item_price*$item_count;
                }
                break;
            //直减
            case 'S':
                $price = $item_price*$item_count-intval($coupon_obj['price']);
                break;
            //折扣率
            case 'D':
                $price = $item_price*$item_count*floatval($coupon_obj['price']);
                break;
            //每满减
            case 'N':
                $price = $item_price*$item_count-intval(($item_price*$item_count)/intval($coupon_obj['coupon_price']))*intval($coupon_obj['price']);
                break;
        }
        return $price;
    }


    //获取各种优惠券的信息
    //判断单品和套装是否有优惠券
    public static function getItemCoupon($id_arr,$user_id,$count_arr)
    {
        $id_arr[]=0;
        $sql = "SELECT 
				sys_item.id,
				sys_item.`name` AS item_name,
				sys_item.price_base,
				sys_item.price_custom,
				MIN(user_coupon.id) AS user_coupon_id,
				prf_coupon.id AS coupon_id,
				prf_coupon.`name`,
				prf_coupon.title,
				prf_coupon.memo,
				prf_coupon.action,
				prf_coupon.action_id,
				prf_coupon.start_time,
				prf_coupon.end_time,
				prf_coupon.coupon_rule,
				prf_coupon.coupon_price,
				prf_coupon.price,
				prf_coupon.user_types,
				prf_coupon.shipping,
				sys_image.url
			FROM `user_coupon`,sys_item,user_info,(
					SELECT 
						IF(pay_user_discount.post_sales_service IS NULL,0,pay_user_discount.post_sales_service) AS service,
						IF(pay_user_discount.sales_type IS NULL,1,pay_user_discount.sales_type) AS sales_type
					FROM user_info LEFT JOIN pay_user_discount ON user_info.user_type = pay_user_discount.user_type AND user_info.user_type_class = pay_user_discount.user_type_class
					WHERE user_info.id = ".$user_id."
				) user_discount, prf_coupon
			LEFT JOIN sys_image ON prf_coupon.img_id = sys_image.id
			WHERE user_coupon.uid = ".$user_id."
			AND user_coupon.useing_time = 0
			AND user_info.id = `user_coupon`.uid
			AND user_discount.sales_type = 1
			AND (sys_item.id = prf_coupon.action_id OR prf_coupon.action_id = 0)
			AND sys_item.id IN(".implode(',', $id_arr).")
			AND user_coupon.coupon_id = prf_coupon.id
			AND (
				  (prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time = 0)
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time = 0)
			)
			AND user_coupon.state = 0
			AND prf_coupon.action = 'item'
			AND prf_coupon.action_id IN (".implode(',', $id_arr).")
			AND prf_coupon.state = 1
			GROUP BY prf_coupon.id;";
        //AND (NOT (prf_coupon.shipping = 0 AND user_discount.service = 0))
        $res = ActiveRecord::findBySql($sql)->asArray()->all();
        $arr = [];
        foreach($res as $key => $row) {
            if ($row['coupon_rule']=='M' && $count_arr[$row['id']]*($row['price_custom']+$row['price_base']) < $row['coupon_price']) {
                continue;
            }
            elseif ($row['coupon_rule']=='N' && $count_arr[$row['id']]*($row['price_custom']+$row['price_base'])/$row['coupon_price'] < 1) {
                continue;
            }
            $arr[$row['user_coupon_id']]=[
                'id'=>$row['user_coupon_id'],
                'coupon_id'=>$row['coupon_id'],
                'name'=>$row['name'],
                'title'=>$row['title'],
                'memo'=>$row['memo'],
                'action'=>$row['action'],
                'action_id'=>$row['action_id'],
                'action_name'=>$row['item_name'],
                'start_time'=>$row['start_time'],
                'end_time'=>$row['end_time'],
                'coupon_rule'=>$row['coupon_rule'],
                'coupon_price'=>$row['coupon_price'],
                'price'=>$row['price'],
                'user_type'=>$row['user_types'],
                'shipping'=>$row['shipping'],
                'url'=>Yii::$app->params['imgPath0'].$row['url'],
            ];
        }
        return $arr;
    }

    //是否有套装优惠券
    public static function getTzCoupon($id_arr,$user_id,$count_arr)
    {
        $id_arr[]=0;
        $sql = "SELECT 
				taozhuang.sid AS id,
				taozhuang.`name` AS item_name,
				MIN(user_coupon.id) AS user_coupon_id,
				prf_coupon.id AS coupon_id,
				prf_coupon.`name`,
				prf_coupon.title,
				prf_coupon.memo,
				prf_coupon.action,
				prf_coupon.action_id,
				prf_coupon.start_time,
				prf_coupon.end_time,
				prf_coupon.coupon_rule,
				prf_coupon.coupon_price,
				prf_coupon.price,
				prf_coupon.user_types,
				prf_coupon.shipping,
				sys_image.url
			FROM `user_coupon`,taozhuang,user_info,(
					SELECT 
						IF(pay_user_discount.post_sales_service IS NULL,0,pay_user_discount.post_sales_service) AS service,
						IF(pay_user_discount.sales_type IS NULL,2,pay_user_discount.sales_type) AS sales_type
					FROM user_info LEFT JOIN pay_user_discount ON user_info.user_type = pay_user_discount.user_type AND user_info.user_type_class = pay_user_discount.user_type_class
					WHERE user_info.id = ".$user_id."
				) user_discount, prf_coupon 
			LEFT JOIN sys_image ON prf_coupon.img_id = sys_image.id
			WHERE user_coupon.uid = ".$user_id."
			AND user_coupon.useing_time = 0
			AND user_info.id = `user_coupon`.uid
			AND user_discount.sales_type = 2
			AND (taozhuang.sid = prf_coupon.action_id OR prf_coupon.action_id = 0)
			AND taozhuang.sid IN(".implode(',', $id_arr).")
			AND user_coupon.coupon_id = prf_coupon.id
			AND (
				  (prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time = 0)
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time = 0)
			)
			AND user_coupon.state = 0
			AND prf_coupon.action = 'set'
			AND prf_coupon.action_id IN (".implode(',', $id_arr).")
			AND prf_coupon.state = 1
			GROUP BY prf_coupon.id;";
        //AND (NOT (prf_coupon.shipping = 0 AND user_discount.service = 0))
        $res = ActiveRecord::findBySql($sql)->asArray()->all();
        $arr = [];
        foreach($res as $key => $row) {
            $tz_price = self::tzPrice($row['id']);
            if ($row['coupon_rule']=='M' && $tz_price*$count_arr[$row['id']] < $row['coupon_price']) {
                continue;
            }
            elseif ($row['coupon_rule']=='N' && ($tz_price*$count_arr[$row['id']]/$row['coupon_price'] < 1)) {
                continue;
            }
            $arr[$row['user_coupon_id']]=[
                'id'=>$row['user_coupon_id'],
                'coupon_id'=>$row['coupon_id'],
                'name'=>$row['name'],
                'title'=>$row['title'],
                'memo'=>$row['memo'],
                'action'=>$row['action'],
                'action_id'=>$row['action_id'],
                'action_name'=>$row['action_id']==0?'套装通用':$row['item_name'],
                'start_time'=>$row['start_time'],
                'end_time'=>$row['end_time'],
                'coupon_rule'=>$row['coupon_rule'],
                'coupon_price'=>$row['coupon_price'],
                'price'=>$row['price'],
                'user_type'=>$row['user_types'],
                'shipping'=>$row['shipping'],
                'url'=>Yii::$app->params['imgPath0'].$row['url'],
            ];
        }
        return $arr;
    }
    public static function tzPrice($tzid)
    {
        global $conn;
        $sql="SELECT SUM(sys_item.price_base+sys_item.price_custom) AS sum_price
			FROM `taozhuang_pos` LEFT JOIN sys_item ON taozhuang_pos.item_id = sys_item.id WHERE taozhuang_pos.tzid=".$tzid." AND taozhuang_pos.pay_state=1;";
        $row = ActiveRecord::findBySql($sql)->asArray()->one();
        return $row['sum_price'];
    }
    //查找品牌优惠券
    public static function getBrandCoupon($item_id_arr,$user_id,$count_arr)
    {
        $item_id_arr[]=0;
        $sql="SELECT DISTINCT
			MIN(user_coupon.id) AS user_coupon_id,
			prf_coupon.id AS coupon_id,
			prf_coupon.`name`,
			prf_coupon.title,
			prf_coupon.memo,
			prf_coupon.action,
			prf_coupon.action_id,
			grp_brand.`name` AS action_name,
			prf_coupon.start_time,
			prf_coupon.end_time,
			prf_coupon.coupon_rule,
			prf_coupon.coupon_price,
			prf_coupon.price,
			prf_coupon.user_types,
			prf_coupon.shipping,
			sys_image.url
		FROM sys_item,user_coupon,grp_brand,user_info,(
					SELECT 
						IF(pay_user_discount.post_sales_service IS NULL,0,pay_user_discount.post_sales_service) AS service,
						IF(pay_user_discount.sales_type IS NULL,1,pay_user_discount.sales_type) AS sales_type
					FROM user_info LEFT JOIN pay_user_discount ON user_info.user_type = pay_user_discount.user_type AND user_info.user_type_class = pay_user_discount.user_type_class
					WHERE user_info.id = ".$user_id."
				) user_discount,prf_coupon
		LEFT JOIN sys_image ON prf_coupon.img_id = sys_image.id
		WHERE prf_coupon.action = 'brand'
		AND user_coupon.useing_time = 0
		AND user_info.id = `user_coupon`.uid
		AND user_discount.sales_type = 1
		AND grp_brand.id = prf_coupon.action_id
		AND user_coupon.uid = ".$user_id."
		AND user_coupon.coupon_id = prf_coupon.id
		AND sys_item.brand_id = prf_coupon.action_id
		AND prf_coupon.state = 1
		AND (
				  (prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time = 0)
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time = 0)
			)
		AND sys_item.id IN(".implode(',', $item_id_arr).")
		GROUP BY prf_coupon.id;";
        //AND (NOT (prf_coupon.shipping = 0 AND user_discount.service = 0))
        $res = ActiveRecord::findBySql($sql)->asArray()->all();
        $coupon = [];
        foreach($res as $key => $row) {
            $coupon[$row['user_coupon_id']]=[
                'id'=>$row['user_coupon_id'],
                'coupon_id'=>$row['coupon_id'],
                'name'=>$row['name'],
                'title'=>$row['title'],
                'memo'=>$row['memo'],
                'action'=>$row['action'],
                'action_id'=>$row['action_id'],
                'action_name'=>$row['action_name'],
                'start_time'=>$row['start_time'],
                'end_time'=>$row['end_time'],
                'coupon_rule'=>$row['coupon_rule'],
                'coupon_price'=>$row['coupon_price'],
                'price'=>$row['price'],
                'user_type'=>$row['user_types'],
                'shipping'=>$row['shipping'],
                'url'=>Yii::$app->params['imgPath0'].$row['url'],
            ];
        }
        $sql2="SELECT id,price_custom,price_base,brand_id FROM sys_item WHERE id IN(".implode(',', $item_id_arr).")";
        $res2 = ActiveRecord::findBySql($sql2)->asArray()->all();
        $item_arr=[];
        foreach($res2 as $key => $row){
            $item_arr[] = $row;
        }
        foreach ($coupon as $key => $value) {
            $price = 0;
            foreach ($item_arr as $i => $item) {
                if ($item['brand_id']==$value['action_id']) {
                    $price=$price+($item['price_base']+$item['price_custom'])*$count_arr[$item['id']];
                }
            }
            if ($price == 0 || $value['coupon_rule']=='M' && $price < $value['coupon_price']) {
                unset($coupon[$key]);
            }
            if ($price == 0 || $value['coupon_rule']=='N' && $price < $value['coupon_price']) {
                unset($coupon[$key]);
            }
        }
        return $coupon;
    }
    //查找类目优惠券
    public static function getClassCoupon($item_id_arr,$user_id,$count_arr)
    {
        if (empty($item_id_arr)) {
            return [];
        }
        $item_id_arr[]=0;
        $sql="SELECT DISTINCT
			MIN(user_coupon.id) AS user_coupon_id,
			prf_coupon.id AS coupon_id,
			prf_coupon.`name`,
			prf_coupon.title,
			prf_coupon.memo,
			prf_coupon.action,
			prf_coupon.action_id,
			grp_class.`name` AS action_name,
			prf_coupon.start_time,
			prf_coupon.end_time,
			prf_coupon.coupon_rule,
			prf_coupon.coupon_price,
			prf_coupon.price,
			prf_coupon.user_types,
			prf_coupon.shipping,
			sys_image.url
		FROM sys_item,user_coupon,grp_class,user_info,(
					SELECT 
						IF(pay_user_discount.post_sales_service IS NULL,0,pay_user_discount.post_sales_service) AS service,
						IF(pay_user_discount.sales_type IS NULL,1,pay_user_discount.sales_type) AS sales_type
					FROM user_info LEFT JOIN pay_user_discount ON user_info.user_type = pay_user_discount.user_type AND user_info.user_type_class = pay_user_discount.user_type_class
					WHERE user_info.id = ".$user_id."
				) user_discount,prf_coupon
		LEFT JOIN sys_image ON prf_coupon.img_id = sys_image.id
		WHERE prf_coupon.action = 'class'
		AND user_coupon.useing_time = 0
		AND user_discount.sales_type = 1
		AND grp_class.id = prf_coupon.action_id
		AND user_coupon.uid = ".$user_id."
		AND user_coupon.coupon_id = prf_coupon.id
		AND sys_item.class_id = prf_coupon.action_id
		AND prf_coupon.state = 1
		AND (
				  (prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time = 0)
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time = 0)
			)
		AND sys_item.id IN(".implode(',', $item_id_arr).")
		GROUP BY prf_coupon.id;";
        //AND (NOT (prf_coupon.shipping = 0 AND user_discount.service = 0))
        $res = ActiveRecord::findBySql($sql)->asArray()->all();
        $coupon = [];
        foreach($res as $key => $row) {
            $coupon[$row['user_coupon_id']]=[
                'id'=>$row['user_coupon_id'],
                'coupon_id'=>$row['coupon_id'],
                'name'=>$row['name'],
                'title'=>$row['title'],
                'memo'=>$row['memo'],
                'action'=>$row['action'],
                'action_id'=>$row['action_id'],
                'action_name'=>$row['action_name'],
                'start_time'=>$row['start_time'],
                'end_time'=>$row['end_time'],
                'coupon_rule'=>$row['coupon_rule'],
                'coupon_price'=>$row['coupon_price'],
                'price'=>$row['price'],
                'user_type'=>$row['user_types'],
                'shipping'=>$row['shipping'],
                'url'=>Yii::$app->params['imgPath0'].$row['url'],
            ];
        }
        $sql2="SELECT id,price_custom,price_base,class_id FROM sys_item WHERE id IN(".implode(',', $item_id_arr).")";
        $res2 = ActiveRecord::findBySql($sql2)->asArray()->all();
        $item_arr=[];
        foreach($res2 as $key => $row){
            $item_arr[] = $row;
        }
        foreach ($coupon as $key => $value) {
            $price = 0;
            foreach ($item_arr as $i => $item) {
                if ($item['class_id'] == $value['action_id']) {
                    $price=$price+($item['price_base']+$item['price_custom'])*$count_arr[$item['id']];
                }
            }
            if ($price == 0 || $value['coupon_rule']=='M' && $price < $value['coupon_price']) {
                unset($coupon[$key]);
            }
            if ($price == 0 || $value['coupon_rule']=='N' && $price < $value['coupon_price']) {
                unset($coupon[$key]);
            }
        }
        return $coupon;
    }
    public static function getAllCoupon($user_id)
    {
        $sql = "SELECT 
				MIN(user_coupon.id) AS user_coupon_id,
				prf_coupon.id AS coupon_id,
				prf_coupon.`name`,
				prf_coupon.title,
				prf_coupon.memo,
				prf_coupon.action,
				prf_coupon.action_id,
				prf_coupon.start_time,
				prf_coupon.end_time,
				prf_coupon.coupon_rule,
				prf_coupon.coupon_price,
				prf_coupon.price,
				prf_coupon.user_types,
				prf_coupon.shipping,
				sys_image.url
			FROM `user_coupon`, prf_coupon
			LEFT JOIN sys_image ON prf_coupon.img_id = sys_image.id
			WHERE user_coupon.uid = ".$user_id."
			AND user_coupon.useing_time = 0
			AND user_coupon.coupon_id = prf_coupon.id
			AND (
				  (prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time < UNIX_TIMESTAMP(NOW()) AND prf_coupon.end_time = 0)
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time > UNIX_TIMESTAMP(NOW()))
				OR(prf_coupon.start_time = 0 AND prf_coupon.end_time = 0)
			)
			AND user_coupon.state = 0
			AND prf_coupon.action = 'all'
			AND prf_coupon.state = 1
			GROUP BY prf_coupon.id;";
        $res = ActiveRecord::findBySql($sql)->asArray()->all();
        $arr = [];
        foreach($res as $key => $row) {
            $arr[$row['user_coupon_id']]=[
                'id'=>$row['user_coupon_id'],
                'coupon_id'=>$row['coupon_id'],
                'name'=>$row['name'],
                'title'=>$row['title'],
                'memo'=>$row['memo'],
                'action'=>$row['action'],
                'action_id'=>$row['action_id'],
                'action_name'=>'全场',
                'start_time'=>$row['start_time'],
                'end_time'=>$row['end_time'],
                'coupon_rule'=>$row['coupon_rule'],
                'coupon_price'=>$row['coupon_price'],
                'price'=>$row['price'],
                'user_type'=>$row['user_types'],
                'shipping'=>$row['shipping'],
                'url'=>Yii::$app->params['imgPath0'].$row['url'],
            ];
        }
        return $arr;
    }
}
